package com.burgeon.backend.SHOPBACKEND.websocket;

import com.burgeon.backend.EnterpriseWeChat.service.EWChatService;
import com.burgeon.backend.SHOPBACKEND.service.AWechatService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@Component
//访问服务端的url地址
@ServerEndpoint(value = "/websocket/{token}/{id}")
public class EWWebSocketServer {

    public static EWChatService ewChatService;


    private static int onlineCount = 0;
    private static ConcurrentHashMap<String, EWWebSocketServer> webSocketSet = new ConcurrentHashMap<>();

    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;
    private final static Log log = LogFactory.getLog(EWWebSocketServer.class);
    private String id = "";
    /**
     * 连接建立成功调用的方法*/
    @OnOpen
    public void onOpen(@PathParam(value = "id") String id,@PathParam(value = "token") String token, Session session) {
        this.session = session;
       // System.err.println(session.isOpen());
        this.id = id;//接收到发送消息的人员编号
        webSocketSet.put(id, this);     //加入set中
        addOnlineCount();           //在线数加1
        log.info("用户"+id+"加入！当前在线人数为" + getOnlineCount());
        try {
            sendMessage("连接成功");
            //如果有未读信息，修改未读消息
        } catch (IOException e) {
            log.error("websocket IO异常");
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        //System.err.println("要移除的"+id);
        webSocketSet.remove(id);  //从set中删除
        subOnlineCount();           //在线数减1

        log.info("有一连接关闭！当前在线人数为" + getOnlineCount());
        //System.err.println("当前连接人数"+webSocketSet.size());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(@PathParam(value = "id") String id,@PathParam(value = "token") String token,String message, Session session) throws JSONException {
        //log.info("来自客户端的消息:" + message);
        this.id = id;
//        System.err.println(id);
        log.info("来自客户端的导购"+id);
      //  System.err.println(message);
        log.info("导购发送信息详细"+message);
        message = JSONTokener(message);
        //{"content":"Hello","msgType":"text","openId":"oWnZCs9Uz2U21NONtIMUg7UcN2V0"}
        JSONObject jsonObj = new JSONObject(message);
       // System.out.println("users" + jsonObj.get("data"));
        String msgType = jsonObj.get("msgType").toString();

        String openId = jsonObj.get("openId").toString();
        //大写转小写
        token = token.toLowerCase();
        System.err.println("转换token================"+token);
        if(msgType.equals("text")){
            String context = jsonObj.get("content").toString();
            ewChatService.messAndroid(context,id,token,msgType);
        }else if(msgType.equals("image")){
            String context = jsonObj.get("content").toString();//这里应该回去图片文件
            ewChatService.messAndroidImage(context,id,token,msgType);
        }


//        JSONObject json1 = new JSONObject(jsonObj.get("data").toString());
//        System.out.println(json1.toString());
//        JSONArray json2 = new JSONArray(json1.get("openid").toString());

        //可以自己约定字符串内容，比如 内容|0 表示信息群发，内容|X 表示信息发给id为X的用户
//        String sendMessage = message.split("[|]")[0];
//        String sendUserId = message.split("[|]")[1];
//        try {
//            if(sendUserId.equals("0"))
//                sendtoAll(sendMessage);
//            else
//                sendtoUser(sendMessage,sendUserId);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }

    }

    public static String JSONTokener(String in)
    {
        // consume an optional byte order mark (BOM) if it exists
        if (in != null && in.startsWith("/ufeff"))
        {
            in = in.substring(1);
        }
        return in;
    }

    /**
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误");
        log.info(error.getMessage());
        error.printStackTrace();
    }

    /**
     *
     * @param message
     * @throws IOException
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
       // this.session.getAsyncRemote().sendText(message);
    }

    /**
     * 发送信息给指定ID用户，如果用户不在线则返回不在线信息给自己
     * @param message
     * @param sendUserId
     * @throws IOException
     */
    public String sendtoUser(String message,String sendUserId) throws IOException {
        String state = "";//
      //  if (session.isOpen() ) {
       // System.err.println("导购的id"+webSocketSet.get(sendUserId));
            if (webSocketSet.get(sendUserId) != null) {
                //System.err.println(sendUserId);
//                if (!id.equals(sendUserId)) {
//                    //System.err.println(session);
//                    //  if(session.isOpen()) {
//                    System.err.println("不等于");
//                    webSocketSet.get(sendUserId).sendMessage(message);
//                    state = "0";
//                    //   }
//                }else {
                    // if(session.isOpen()) {
                log.info("用户发送的消息"+message);
                    webSocketSet.get(sendUserId).sendMessage(message);
                    //   }
                    state = "0";
//                }
            } else {
                //System.err.println(id);
                //System.err.println("导购不在线");
                //如果用户不在线则返回不在线信息给自己
                //sendtoUser("当前用户不在线",id);
                log.info("导购不在线");
                state = "1";
            }

       // }
        return state;
    }

    /**
     * 发送信息给所有人
     * @param message
     * @throws IOException
     */
    public void sendtoAll(String message) throws IOException {
        for (String key : webSocketSet.keySet()) {
            try {
                webSocketSet.get(key).sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    public static synchronized int getOnlineCount() {
        //System.err.println("getOnlineCount"+onlineCount);
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        EWWebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        EWWebSocketServer.onlineCount--;
    }
}
